<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="库位编码" prop="areaCode">
        <el-input
          v-model="queryParams.areaCode"
          placeholder="请输入库位编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位名称" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          placeholder="请输入库位名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['area:area:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['area:area:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['area:area:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['area:area:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="areaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库位编码" align="center" prop="areaCode" width="200px"/>
      <el-table-column label="库位名称" align="center" prop="areaName" />
      <el-table-column label="面积" align="center" prop="area"/>
      <el-table-column label="最大载重量" align="center" prop="maxLoa" />
      <el-table-column label="库位位置X" align="center" prop="positionX" />
      <el-table-column label="库位位置y" align="center" prop="positionY" />
      <el-table-column label="库位位置z" align="center" prop="positionZ" />
      <el-table-column label="是否冻结" align="center" prop="enableFlag" >
        <template #default="scope">
          <el-switch 
            v-model="scope.row.enableFlag" 
            active-value="N"
            inactive-value="Y"
            active-text="是" 
            inactive-text="否"
            @change="handleEnableChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['area:area:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['area:area:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库位设置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body @close="resetDialogForm">
      <el-row :gutter="15">
      <el-form ref="areaRef" :model="form" :rules="rules" size="default" label-width="100px">
        <el-col :span="14">
          <el-form-item label="库位编码" prop="areaCode">
            <el-input v-model="form.areaCode" type="text" placeholder="请输入库位编码" clearable
              :style="{width: '100%'}"></el-input>
               <!-- 自动生成 -->
              <el-switch 
                    v-model="autoGenerateCode" 
                    style="margin-left: 10px;"
                    @change="handleCodeSwitchChange" 
                  ></el-switch>
              <span style="margin-left: 5px;">自动生成</span>
          </el-form-item>
        </el-col>
        <el-col :span="21">
          <el-form-item label="库位名称" prop="areaName">
            <el-input v-model="form.areaName" type="text" placeholder="请输入库位名称" clearable
              :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-row gutter="15">
            <el-col :span="11">
              <el-form-item label="面积" prop="area">
                <el-input-number v-model="form.area" placeholder="0"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="最大载重量" prop="maxLoa">
                <el-input-number v-model="form.maxLoa" placeholder="0"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        
        <el-col :span="24">
          <el-row gutter="15">
            <el-col :span="8">
              <el-form-item label="库位位置X" prop="positionX">
                <el-input-number v-model="form.positionX" placeholder="0"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="库位位置Y" prop="positionY">
                <el-input-number v-model="form.positionY" placeholder="0"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="库位位置Z" prop="positionZ">
                <el-input-number v-model="form.positionZ" placeholder="0"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"
              :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    </el-dialog>
  </div>
</template>

<script setup name="Area">
import { listArea, getArea, delArea, addArea, updateArea,updatearea1 } from "@/api/area/area"

const { proxy } = getCurrentInstance()
// 新增：自动生成编码开关状态
const autoGenerateCode = ref(false)
const areaList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
//取下当前库位id
import { useRoute } from 'vue-router'
const route = useRoute()
//获取当前仓库id
const locationId1 = route.params.locationId 

/** 生成库区编码（规则：WS-YYYYMMDDHHmmss，如WS-20240520143025） */
function generateWorkshopCode() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  const code = `KW-${year}${month}${day}${hour}${minute}${second}`
  form.value.areaCode = code
}

/** 自动生成开关变化事件 */
function handleCodeSwitchChange() {
  if (autoGenerateCode.value) {
    generateWorkshopCode()
  } else {
    form.value.areaCode = null  // 关闭时清空手动输入
    
  }
}

// 表单ref（与模板中ref="warehouseRef"对应）
const warehouseRef = ref();
// 对话框关闭时：重置表单 + 关闭开关
function resetDialogForm() {
  // 关闭“自动生成”开关
  autoGenerateCode.value = false;

  // 清除验证状态
  if (warehouseRef.value) {
    warehouseRef.value.clearValidate(); // 清除所有字段验证
  }
  // 清空表单数据
  data.form = {};
  open.value = false;
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    areaCode: null,
    areaName: null,
  },
  rules: {
    areaCode: [
      { required: true, message: "库位编码不能为空", trigger: "blur" }
    ],
    areaName: [
      { required: true, message: "库位名称不能为空", trigger: "blur" }
    ],
    locationId: [
      { required: true, message: "库区ID不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
import { ElMessage, ElMessageBox } from 'element-plus'

//是否启用开关
const handleEnableChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `你确认要${row.enableFlag === 'N' ? '冻结' : '启用'}‘${row.areaName}’仓库吗?`,
      '系统提示',
      {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }
    );
    // 用户确认后执行更新
    const response = await updatearea1(row);
    console.log(response);
    
    if (response.code==200) {
      ElMessage.success("操作成功");
      getList()
    } else {
      ElMessage.error("操作失败");
      getList()
    }
  } catch (error) {
    getList() 
    ElMessage.success("取消成功");   
  }
}


/** 查询库位设置列表 */
function getList() {
  loading.value = true
  listArea(queryParams.value).then(response => {
    areaList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    areaId: null,
    areaCode: null,
    areaName: null,
    locationId: locationId1,
    area: null,
    maxLoa: null,
    positionX: null,
    positionY: null,
    positionZ: null,
    enableFlag: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("areaRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.areaId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  console.log("新增");
  
  reset()
  open.value = true
  title.value = "添加库位设置"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _areaId = row.areaId || ids.value
  getArea(_areaId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改库位设置"
  })
}

/** 提交按钮 */
function submitForm() {
  form.value.locationId=locationId1
  proxy.$refs["areaRef"].validate(valid => {
    if (valid) {
      if (form.value.areaId != null) {
        updateArea(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addArea(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _areaIds = row.areaId || ids.value
  proxy.$modal.confirm('是否确认删除库位设置编号为"' + _areaIds + '"的数据项？').then(function() {
    return delArea(_areaIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('area/area/export', {
    ...queryParams.value
  }, `area_${new Date().getTime()}.xlsx`)
}

getList()
</script>
